<template>
  <div class="wrapper">
    <el-row :gutter="10" style="margin-bottom: 10px">
      <el-col :span="12">
        <div class="label">车辆编号</div>
        <el-input placeholder="车辆编号" size="small" v-model="paramsState.carNumber" style="width: 200px">
        </el-input>
        <el-button style="margin-left: 10px" type="primary" size="small" icon="el-icon-search"
                   @click="search">搜索
        </el-button>
        <el-button style="margin-left: 10px" type="primary" size="small" icon="el-icon-download"
                   @click="downloadList">批量下载
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <el-table :data="tableData" v-loading="listLoading" border @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          fixed
          align="center"
          width="45">
      </el-table-column>
      <el-table-column show-overflow-tooltip v-for="field in fields" :key="field.prop" :prop="field.prop"
                       :label="field.label"
                       :width="field.width" :align="field.align">
      </el-table-column>
      <el-table-column label="操作" width="250" align="center" fixed="right">
        <template v-slot="{ row }">
          <el-button type="text" title="检查图片" @click="lookImages(row)">检查图片</el-button>
          <el-button type="text" title="查看" @click="handle(row)">查看</el-button>
          <el-button type="text" title="文档下载" @click="downloadFile(row.wordUrl)">文档下载</el-button>
          <el-button type="text" title="删除" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination :current-page="paramsState.startpoint" :page-size="paramsState.nums" :total="paramsState.total"
                   :page-sizes="[5, 10, 20, 30]" style="padding: 20px 0"
                   layout="prev, pager, next, jumper, ->, sizes, total"
                   @current-change="currentChange" @size-change="sizeChange"/>

    <!-- 查看 or 编辑框-->
    <el-dialog :title="findData.readonly ? '查看' : '编辑'" width="800px" :visible.sync="Visible" @closed="resetDialog">
      <el-form v-loading="loading" size="small" class="formRow" label-position="top">
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="车牌号" prop="carNumber">
              <el-input style="margin-top: 10px" v-model="findData.carNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="记录创建时间" prop="createTime">
              <el-input style="margin-top: 10px" v-model="findData.createTime"></el-input>

              <!--              <el-date-picker style="margin-top: 10px;" class="w100" v-model="findData.createTime"-->
              <!--                              type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期">-->
<!--              </el-date-picker>-->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运单号" prop="waybillNumber">
              <el-input style="margin-top: 10px" v-model="findData.waybillNumber"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="驾驶员" prop="driver">
              <el-input style="margin-top: 10px" v-model="findData.driver"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="押运员" prop="escort">
              <el-input style="margin-top: 10px" v-model="findData.escort"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货物起始位置" prop="departure">
              <el-input style="margin-top: 10px" v-model="findData.departure"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="货物送达地址" prop="destination">
              <el-input style="margin-top: 10px" v-model="findData.destination"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货物名称" prop="goodsName">
              <el-input style="margin-top: 10px" v-model="findData.goodsName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货物数量" prop="goodsQuantity">
              <el-input style="margin-top: 10px" v-model="findData.goodsQuantity"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="运输总里程" prop="mileage">
              <el-input style="margin-top: 10px" v-model="findData.mileage"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-input style="margin-top: 10px" v-model="findData.status"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务完成时间" prop="completionTime">
              <el-date-picker class="w100" v-model="findData.completionTime" type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-row :gutter="12">-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="司机签名链接" prop="driverSealLink">-->
        <!--              <upload v-model="findData.driverSealLink" />-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="押运员签名链接" prop="escortSealLink">-->
        <!--              <upload v-model="findData.escortSealLink" />-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
      </el-form>

      <!--      <div slot="footer">-->
      <!--        <el-button v-if="!findData.readonly" type="primary" @click="onSubmit">提交</el-button>-->
      <!--      </div>-->
    </el-dialog>
    <el-dialog title="检查图片" width="800px" :visible.sync="imagesVisible" @closed="resetDialog">
      <el-form size="small" class="formImages" label-position="top" v-if="imagesVisible">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="驾驶员签名">
              <el-image class="image" :src="findData.driverSealLink" lazy :preview-src-list="[findData.driverSealLink]"
                        fit="cover">
                <div slot="placeholder" class="image-slot">
                  加载中<span class="dot">...</span>
                </div>
              </el-image>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="押运员签名">
              <el-image class="image" :src="findData.escortSealLink" lazy :preview-src-list="[findData.escortSealLink]"
                        fit="cover">
                <div slot="placeholder" class="image-slot">
                  加载中<span class="dot">...</span>
                </div>
              </el-image>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {Delete_traffic_log, Query_traffic_log} from "@/api"
import upload from "../driverList/components/upload.vue"
import moment from "moment"
import {downloadFile} from "@/utils/index"

export default {
  name: "line",
  components: {
    upload
  },
  data() {
    return {
      // 加载
      listLoading: false,
      // 详情弹窗
      Visible: false,
      updateVisible: false,
      // 搜索用户相关
      paramsState: {
        carNumber: '',
        startpoint: 1,
        nums: 10,
        total: 0
      },
      // 用户列表相关
      tableData: [],
      // 详情加载中
      loading: false,
      type: 'rgxd',

      // 操作的数据信息
      findData: {
        carNumber: '',
        createTime: '',
        waybillNumber: '',
        driver: '',
        escort: '',
        departure: '',
        destination: '',
        goodsName: '',
        goodsQuantity: '',
        mileage: '',
        status: '',
        completionTime: '',
        driverSealLink: '',
        escortSealLink: ''
      },
      fields: [
        {label: '车牌号', prop: 'carNumber', width: '150', align: 'center'},
        {label: '创建时间', prop: 'createTime', width: '150', align: 'center'},
        {label: '运单号', prop: 'waybillNumber', width: '230', align: 'center'},
        {label: '驾驶员', prop: 'driver', width: '', align: 'center'},
        {label: '押运员', prop: 'escort', width: '', align: 'center'},
        {label: '货物起始位置', prop: 'departure', width: '230', align: 'center'},
        {label: '货物送达地址', prop: 'destination', width: '230', align: 'center'},
        {label: '货物名称', prop: 'goodsName', width: '150', align: 'center'},
        {label: '货物数量', prop: 'goodsQuantity', width: '', align: 'center'},
        {label: '运输总里程', prop: 'mileage', width: '', align: 'center'},
        {label: '状态', prop: 'status', width: '', align: 'center'},
        {label: '完成时间', prop: 'completionTime', width: '230', align: 'center'}
      ],
      imagesVisible: false,
      multipleSelection: []

    }
  },
  methods: {
    downloadFile,
    // 批量下载
    downloadList() {
      const length = this.multipleSelection.length;
      if (length <= 0) {
        this.$message({
          message: '请选择数据',
          type: 'warning'
        });
        return;
      }

      this.$confirm(`确定要下载选中的${length}条数据吗`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.multipleSelection.forEach(item => {
          downloadFile(item.wordUrl);
        })
      })
    },
    // 表格选择事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 检查图片
    lookImages(row) {
      console.log(row)
      this.imagesVisible = true
      this.findData = {
        ...row
      }
    },
    dateFormat(date) {
      let expirationDate = moment(date)
      // 获取当前时间
      let now = moment()
      // 计算时间差
      let duration = moment.duration(expirationDate.diff(now)).days()
      if (duration < 0) {
        return "已过期"
      } else {
        return duration + "天"
      }
    },
    change(file) {
      let _this = this
      console.log(file.raw)
      let reader = new FileReader()
      reader.onload = function (event) {
        let base64 = event.target.result
        _this.findData.headimg = base64
      }
      reader.readAsDataURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const types = ['image/jpeg', 'image/png']
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!types.includes(file.type)) {
        this.$message.error('上传头像图片只能是 JPG 和 PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    changeDate(event) {
      if (event) {
        let times = event.map(item => this.format(item))
        let [startTime, endTime] = times
        this.paramsState.startTime = startTime
        this.paramsState.endTime = endTime
      }
      this.paramsState.pageCurrent = 1
      this.getList()

    },
    format(time, end = "HH:mm:ss") {
      return moment(time).format(`YYYY-MM-DD ${end}`)
    },
    // 获取用户列表数据
    async getList() {
      this.listLoading = true
      try {
        let params = {
          ...this.paramsState
        }

        delete params.time
        delete params.total

        let result = await Query_traffic_log(params)
        this.tableData = result.data
        this.listLoading = false

        this.paramsState.total = result.total

        // this.findData.createTime = format(result.data.createTime)

        // this.formattedDates = result.data.map(item => {
        // 	return {
        // 		...item,
        // 		createTime: this.format(item.createTime)
        // 	}
        // })
        // console.log(formattedDates)

        // console.log(result.data)
        result.data.forEach(e => {
          console.log(e.createTime)
        })

      } catch (error) {
        this.listLoading = false
        this.$message.error("获取列表失败，请重试")
      }
    },
    // 根据用户输入进行查询
    search() {
      this.paramsState.startpoint = 1
      this.getList()
    },
    sizeChange(e) {
      this.paramsState.nums = e
      this.getList()
    },
    currentChange(e) {
      this.paramsState.startpoint = e
      this.getList()
    },
    resetDialog() {
      this.findData = {}
    },
    // 保存
    onSubmit() {
      let params = {
        ...this.findData
      }
      if (params.member_end_time) {
        params.member_end_time = moment(params.member_end_time).format('YYYY-MM-DD HH:mm:ss')
      }
      console.log(params, "提交参数")

      modify_escort(params).then(result => {
        console.log(result, "处理订单")
        this.$message.success(result.msg)
        this.getList()
        this.Visible = false
      })
    },
    // 显示详情
    handle(row, readonly = false) {
      let params = {
        ...row,
        readonly
      }
      if (params.member_end_time) {
        params.member_end_time = new Date(params.member_end_time)
      }
      this.findData = params
      this.Visible = true
    },
    // 操作
    update(row) {
      this.findData = {
        id: row.id
      }
      this.updateVisible = true
    },
    // 删除用户
    handleDelete(row) {
      this.$confirm('此操作将永久删除该用户,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Delete_traffic_log({id: row.id}).then(() => {
          this.$message({
            type: 'success', message: '删除成功!'
          })
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info', message: '已取消删除'
        })
      })
    }
  },
  async mounted() {
    await this.getList()
  }
}
</script>

<style lang="scss" scoped>
.table-avatar {
  width: 40px;
  height: 40px;
}

::v-deep .image-table-slot {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #eee;
}

.wrapper {
  margin: 20px;

  .image {
    width: 100%;
    max-height: 250px;
  }

  .label {
    font-size: 14px;
    color: #333;
    padding-bottom: 10px;
  }
}

::v-deep .el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

::v-deep .el-dialog__body {
  padding: 10px 20px;
}

.formRow {

  &.disabled {
    pointer-events: none;
  }


  .el-col {
    padding: 8px 0;

    .label {
      font-weight: 500;
      margin-right: 10px;
      color: #444;
    }

    .headimg_view {
      margin-left: 50%;
      transform: translateX(-50%);
      overflow: hidden;

      .avatar {
        width: 120px;
        height: 120px;
        font-size: 0;
      }

      ::v-deep .image-slot {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        background-color: #eee;

        .iocn {
          font-size: 20px;
        }

        span {
          font-size: 14px;
        }
      }
    }
  }

  .sourceList {
    .item {
      padding: 10px;
      background-color: #f8f8f8;
      border-bottom: 1px solid #ddd;

      &:last-child {
        border-bottom: 0;
      }

      .box {
        padding: 5px 0;
        display: flex;

        .label {
          color: #666;
          padding-right: 20px;
        }
      }
    }
  }
}

.dataList {
  margin-bottom: 20px;

  .desc {
    margin-top: 10px;
    color: #888;
  }

  .dataTitle {
    font-weight: 500;
    color: #333;
  }
}

//::v-deep .el-form-item__label {
//  width: 100%;
//}

.flex {
  display: flex;

  span {
    b {
      color: #f46162;
    }
  }

  &.between {
    justify-content: space-between;
  }
}
</style>
